var hlp = {
    parseDatetime: function(str, format) {
        var y = str.match(/([0-9]+)-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+/)[1];
        var m = str.match(/[0-9]+-([0-9]+)-[0-9]+ [0-9]+:[0-9]+:[0-9]+/)[1];
        var d = str.match(/[0-9]+-[0-9]+-([0-9]+) [0-9]+:[0-9]+:[0-9]+/)[1];
        var h = str.match(/[0-9]+-[0-9]+-[0-9]+ ([0-9]+):[0-9]+:[0-9]+/)[1];
        var i = str.match(/[0-9]+-[0-9]+-[0-9]+ [0-9]+:([0-9]+):[0-9]+/)[1];
        var s = str.match(/[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:([0-9]+)/)[1];
        var result = format;
        result = result.replace('y', y);
        result = result.replace('m', m);
        result = result.replace('d', d);
        result = result.replace('h', h);
        result = result.replace('i', i);
        result = result.replace('s', s);
        return result;
    }
};
var lst = {
    statuses: {
        list: [{
            id: 0,
            ident: 'New'
        },
        {
            id: 1,
            ident: 'Active'
        },
        {
            id: 2,
            ident: 'Resolved'
        },
        {
            id: 3,
            ident: 'Deleted'
        },
        {
            id: 4,
            ident: 'Waiting user'
        }],
        getById: function(id) {
            for (var i in lst.statuses.list) {
                if (id - 0 == lst.statuses.list[i].id - 0) {
                    return lst.statuses.list[i];
                }
            }
            return false;
        }
    },
	excases: {
        list: [],
        listLoad: function() {
            return $.Deferred(function(def) {		  
				$.post('/Tickets/RF201',
					function(results){
						    lst.excases.list = results;
                            def.resolve(true);
					},
					'json'
				);
            }).promise();
        },
        getById: function(id) {
            for (var i in lst.excases.list) {
                if (id - 0 == lst.excases.list[i].id - 0) {
                    return lst.excases.list[i];
                }
            }
            return false;
        }
    }
};
var pageNum = 1;
var pageSize = 10;
var tickets = {
    getList: function(params) {	
		//wObj(results);
		 return $.Deferred(function(def) {
			$.post('/Tickets/RF200',
			{'page': pageNum,'rows': pageSize,},
			function(results){				   
						def.resolve(results);
				},
				'json'
			);
		}).promise();		
    },
	showList: function(results) {
        $('#ticket_pagination').pagination({
            total: results['get_count_search'],
            pageNumber: pageNum,
            pageSize: pageSize,
            loading: true,
            displayMsg: '',
            showRefresh: false,			
            onSelectPage: function(pageNum1,pageSize1) {
			    pageNum = pageNum1,
                pageSize = pageSize1,
                tickets.getList({}).then(function(results) {
                    tickets.showList(results);
                    if (results['get_result_search'].length) {
                        tickets.getById(results['get_result_search'][0].addid).then(function(result) {
                            tickets.showDataTicket(result)
                        });
                    } else {
                        tickets.clearPriorId();
                    }
                })
            }
        });
        $("#ticket_list").html('');
        for (var i in results['get_result_search']) {
            var style = '';
            if (results['get_result_search'][i].status - 0 > 1) style += 'color: gray;';
            if (results['get_result_search'][i].ticket_for_processing_admin_status - 0 == 3 || results['get_result_search'][i].ticket_for_processing_admin_status - 0 == 7) style += 'color: green;';
            if (results['get_result_search'][i].ticket_for_processing_admin_status - 0 == 4 || results['get_result_search'][i].ticket_for_processing_admin_status - 0 == 8) style += 'color: red;';
            $("#ticket_list").append('<div class="ticket_title" id="ticket_row_' + results['get_result_search'][i].addid + '">' + '<a href="#" onclick="tickets.getById(' + results['get_result_search'][i].addid + ').then(function(result) {tickets.showDataTicket(result)}); return false;" style="' + style + '" >' + 'T' + results['get_result_search'][i].addid + ": " + results['get_result_search'][i].name + '</a>' + (results['get_result_search'][i].m >= 1 ? ' <span class="unread">(' + results['get_result_search'][i].m + ')</span>': '') + '</div>');
        }
    },
	getById: function(id_ticket) {
		loadingShow();
		return $.Deferred(function(def) {					   
			$.post('/Tickets/RF203',
			{'id': id_ticket},
			function(results){
				loadingHide();
				  def.resolve(results);
				},
				'json'
			);
			 /**/
		}).promise();
    },
	showDataTicket: function(data) {
		$('#ticket_view').html('');
        var ticket = data.ticket;
        var messages = data.ticket_messages;	
        var ticket_for_processing_admin = data.ticket_for_processing_admin;
        $("#ticket_list").children().removeClass('active');
        if ($("#ticket_row_" + ticket.addid).length != 0) {
            $("#ticket_row_" + ticket.addid).addClass('active');
        }
        var html = '';
        html += '<h1>T' + ticket.addid + ': ' + ticket.name + '</h1>';
        html += '<h2>' + getTranslation('Excase') + ': ' + getTranslation(lst.excases.getById(ticket.id_excase).name) + '</h2>';
        html += '<p>';
        html += getTranslation('Status') + ': ' + getTranslation(lst.statuses.getById(ticket.status).ident) + ' ';

		if (ticket.status - 0 != 3) html += '<a onclick="tickets.setStatus(' + ticket.addid + ', 3); return false;" iconcls="icon-ok" class="easyui-linkbutton l-btn" href="#">' + getTranslation('Delete') + '</a> ';
        html += '</p>';
        html += '<div>';
        for (var i in messages) {
            var html_images = '';
            if (messages[i].files) {
                for (var j = 0; j < messages[i].files.length; j++) html_images += '<span>' + messages[i].files[j].filename + '</span>';
            }
            
			html += '<div style="border-radius: 10px; padding: 10px; margin: 10px 0; ' + (messages[i].id_user - 0 == 1 ? 'background: #ffffff; border: solid 1px #cfcfcf;': 'background: #fee996; border: 1px solid #d19405;') + ' ' + (messages[i].status - 0 == 1 ? 'opacity: 0.5;': '') + '">';
			
            html += '<h3>' + (messages[i].cache_name ? messages[i].cache_name: '-') + '</h3>';
            var msg_escapes = messages[i].msg + '';
            if (messages[i].is_ident - 0 == 1) msg_escapes = getTranslation(msg_escapes);
            msg_escapes = msg_escapes.replace(/\n/g, '<br>').replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/&lt;br&gt;/g, "<br>");
            html += '<p>' + msg_escapes + '</p>';
            html += '<p>' + (messages[i].crtime ? hlp.parseDatetime(messages[i].crtime, 'd.m.y h:i:s') + ' ': '') + '</p>';
            html += '<p>' + html_images + '</p>';
            html += '<div style="clear: both;"></div>';
            html += '</div>';
        }
        html += '</div>';
        html += '</p>';
        if (ticket.status - 0 == 2) {
            html += '<p style="padding: 20px;">' + getTranslation("ticket_closed_text_by_structure") + '</p>';
        }
        html += '<form action="" method="post" id="form_reply" style="padding: 10px; border: 1px solid #d19405; background: #fee996; border-radius: 10px;">';
        html += '<textarea id="msg_reply" style="width: 99%;"></textarea>';
        html += '<div id="add_ticket_comment_files" name="new_ticket_comment"></div>';
        html += '<div class="clear"></div>';
        html += '<div style="padding-top:10px;">';
        html += '<a href="#" class="easyui-linkbutton" iconCls="icon-save" hotkey="Ctrl + Enter" onclick="tickets.addMessage(' + ticket.addid + '); return false;">'+getTranslation("Save")+'</a>';
        html += '</div>';
        html += '</form>';
        $('#ticket_view').html(html);
        if (ticket.status - 0 == 2) {
            $('#form_reply').hide()
        }
        $('#ticket_view .easyui-linkbutton').linkbutton({
            iconCls: $(this).attr('iconCls')
        });
        //createUploader(document.getElementById('add_ticket_comment_files'))
	/*	*/
    },
    clearPriorId: function() {
        $('#ticket_view').html('');
        $('#user_info').html('');
        $('#user_tickets').html('');
    },
	addMessage1: function(id_ticket,text) {
		return $.Deferred(function(def) {
			$.post('/Tickets/RF300',
			{'id': id_ticket,'text':text},
			function(results){		   
				  def.resolve(results);
				},
				'json'
			);
			 /**/
		}).promise();
    },
	addMessage: function(id_ticket) {
        $('#form_reply textarea').removeClass('error');
        if ($('#form_reply textarea').val() == '') {
            $('#form_reply textarea').addClass('error');
        } else {
            $('#form_reply textarea').removeClass('error');
            return tickets.addMessage1(id_ticket, $('#form_reply textarea').val()).then(function() {
                tickets.getById(id_ticket).then(function(result) {
                    tickets.showDataTicket(result);
                },
                function(result) {
                    showAlert(result);
                });
            });
        }
    },
	setStatus1: function(id_ticket, status) {
		return $.Deferred(function(def) {
			$.post('/Tickets/RF206',
			{'id': id_ticket},
			function(results){				   
				  def.resolve(results);
				},
				'json'
			);
			 /**/
		}).promise();	
	},
	setStatus: function(id_ticket, status) {
        tickets.setStatus1(id_ticket, status).then(function() {
            tickets.getList({}).then(function(results) {
                tickets.showList(results);
                if (results['get_result_search'].length) {
                    tickets.getById(results['get_result_search'][0].id).then(function(result) {
                        tickets.showDataTicket(result);
                    });
                } else {
                    tickets.clearPriorId();
                }
            });
        });
    },
	showFaq: function() {
        if ($('#ticket_add_pref').length == 0) {
            var html = '<div id="ticket_add_pref" style="dislay:none; padding:30px; overflow:auto; height:550px;">' + '<div class="china_text">' + '<span>' + getTranslation('tickets_pref_add_text_china') + '</span>' + '</div>' + '<div style="padding-top:20px; padding-bottom:20px; text-align:center;">' + '<a href="#" class="easyui-linkbutton" iconCls="icon-add" onclick="tickets.hideFaq(); tickets.showAddForm(); return false;" id="ticket_button_next">' + getTranslation('Create') + '</a>' + '<span class="timeLeft" style="padding: 5px 10px; color: gray;"></span>' + '</div>' + '</div>';
            $('body').append(html);
        }
        $('#ticket_add_pref .easyui-linkbutton').linkbutton();
       // $('#ticket_add_pref #ticket_button_next').linkbutton('disable');
        $('#ticket_add_pref .timeLeft').html('');
        $('#ticket_add_pref').show();
        $('#ticket_add_pref').dialog({
            width: 750,
            title: getTranslation(getTranslation('Create ticket')),
            modal: true,
            closed: false
        });
       // var SecondsLeft = 30;
        if (window.interval1) {
            clearInterval(window.interval1);
            window.interval1 = undefined;
        }
        window.interval1 = setInterval(function() {
            SecondsLeft = SecondsLeft - 1;
            $('#ticket_add_pref .timeLeft').html(' ' + SecondsLeft);
            if (SecondsLeft <= 0) {
                $('#ticket_add_pref #ticket_button_next').linkbutton('enable');
                $('#ticket_add_pref .timeLeft').html('');
                clearInterval(window.interval1);
                window.interval1 = undefined;
            }
        },
        1000);
    },
    hideFaq: function() {
        $("#ticket_add_pref").dialog("close");
    },
	showAddForm: function() {
        if ($('#ticket_add').length == 0) {
            var html_excase_select = '';
            html_excase_select += '<select name="id_excase" style="width: 520px;">';
            var excases = [{
                id: '',
                name: 'tickets_select_excase'
            }];
            for (var i in lst.excases.list) {
                    var tmp = $.extend(true, {},lst.excases.list[i]);
                    excases.push(tmp);
            }
            for (var i = 0; i < excases.length; i++) {
                html_excase_select += '<option value="' + excases[i].id + '">' + getTranslation(excases[i].name) + '</option>';
            }
            html_excase_select += '</select>';
            var html = '';
            html += '<div id="ticket_add" iconCls="icon-add" style="display:none; padding-bottom:30px; overflow:auto; height:550px;">';
            html += '<form id="ticket_add_form" method="POST">';
            html += '<input type="hidden" name="a" value="add_new_ticket">';
            html += '<table align="center" width=100%><tr>';
            html += '<th colspan="4" style="padding-top:20px; padding-bottom:10px;text-align:center;">' + getTranslation('ticket_create_info') + '</th>';
            html += '</tr><tr>';
            html += '<td align="right"><span class="translate">Excase</span> *</td>';
            html += '<td align="left" colspan="3">' + html_excase_select + '</td>';
            html += '</tr><tr>';
            html += '<td align="right"><span class="translate">Title</span> *</td>';
            html += '<td align="left" colspan="3"><input onkeyup="if ($(this).val().trim() != \'\') { $(this).removeClass(\'error\'); }" type="text" name="title" id=ticket_new_title style="width:520px;"/></td>';
            html += '</tr><tr>';
            html += '<td align="right" valign="top" nowrap><span class="translate">Your message</span> *</td>';
            html += '<td align="left" colspan="3"><textarea onkeyup="if ($(this).val().trim() != \'\') { $(this).removeClass(\'error\'); }" name="message" style="height:150px; width:520px;"></textarea></td>';
            html += '</tr><tr>';
            html += '<td align="right" valign="top"><span class="translate">Files</span></td>';
            html += '<td align="left" colspan="3"><div id="add_ticket_files" name="new_ticket"></div></td>';
            html += '</tr></table>';
            html += '</form>';
            html += '</div>';
            html += '<div id="ticket_add_buttons" style="display:none; height: 28px;">';
            html += '<a href="#" class="easyui-linkbutton" iconCls="icon-save" onclick="tickets.createNew(); return false;">' + getTranslation("Save") + '</a>';
            html += '<a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="tickets.hideAddForm(); return false;">' + getTranslation("Close") + '</a>';
            html += '</div>';
            $('body').append(html);
        }
        $('#ticket_add input[name=title]').removeClass('error');
        $('#ticket_add textarea[name=message]').removeClass('error');
        $('#ticket_new_title').val('');
        $('#ticket_add textarea').val('');
        $('#ticket_add').show();
        $('#ticket_add').dialog({
            width: 750,
            title: getTranslation(getTranslation('Create ticket')),
            buttons: '#ticket_add_buttons',
            modal: true
        });
        $('#ticket_add_buttons .easyui-linkbutton').linkbutton({
            iconCls: $(this).attr('iconCls')
        });
    },
    hideAddForm: function() {
        $('#ticket_add').dialog('close');
    },
	AddFormpost: function(title,message,id_excase) {
		return $.Deferred(function(def) {
			$.post('/Tickets/RF303',
			{'title': title,'message': message,'id_excase': id_excase},
			function(results){
				  def.resolve(results);
				},
				'json'
			);
		}).promise();	

    },
	
    createNew: function() {
		var id_ticket=$('#ticket_add input[name=title]').val().trim();
		var message=$('#ticket_add textarea[name=message]').val().trim();
		var id_excase=$('#ticket_add select[name=id_excase]').val();
		
		
        $('#ticket_add input[name=title]').removeClass('error');
        $('#ticket_add textarea[name=message]').removeClass('error');
        if (id_ticket == '' || message == '' || id_excase=='') {
            if (id_ticket == '') $('#ticket_add input[name=title]').addClass('error');
            if (message == '') $('#ticket_add textarea[name=message]').addClass('error');
			 return false;

        }
		
        tickets.AddFormpost(id_ticket,message,id_excase).then(function() {
            tickets.hideAddForm();
            tickets.getList({}).then(function(results) {
                tickets.showList(results);
                if (results['get_result_search'].length) {
                    tickets.getById(results['get_result_search'][0].id).then(function(result) {
                        tickets.showDataTicket(result);
                    });
                } else {
                    tickets.clearPriorId();
                }
            });
        },
        function(result) {
            if (result == 'id_excase not int format') {
                showAlert(getTranslation('tickets_select_excase_message'));
            } else {
                showAlert(result);
            }
        });
    }
	
};

$(document).ready(function() {
    lst.excases.listLoad().then(function() {
        tickets.getList({}).then(function(results) {
            tickets.showList(results);
            if (results['get_result_search'].length) {
                tickets.getById(results['get_result_search'][0].addid).then(function(result) {														 
                    tickets.showDataTicket(result);
                });
            } else {
                tickets.clearPriorId();
            }
        });
    });
});